/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package botlab.gui.actionlistener;

import botlab.gui.GUI;
import botlab.gui.filefilter.CustomFileFilter;
import com.Ostermiller.Syntax.HighlightedDocument;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFileChooser;
import javax.swing.SwingUtilities;

/**
 *
 * @author Quentin
 */
public class OpenActionListener implements ActionListener
{
    private GUI gui;
    private final JFileChooser fc;
    
    public OpenActionListener(GUI gui)
    {
        this.gui=gui;
        fc=new JFileChooser();
        fc.setAcceptAllFileFilterUsed(false);
        fc.addChoosableFileFilter(new CustomFileFilter("botlab","Botlab's file type (.botlab)"));
        fc.addChoosableFileFilter(new CustomFileFilter("txt","Text file type (.txt)"));
    }
    
    public void actionPerformed(ActionEvent e)
    {
        int returnVal = fc.showOpenDialog(gui.getFrame());
        
        if (returnVal == JFileChooser.APPROVE_OPTION) 
        {
            File file = fc.getSelectedFile();
            try
            {
                StringBuilder str = new StringBuilder();
                List<String> l = Files.readAllLines(file.toPath(), StandardCharsets.UTF_8);
                
                for(int i=0;i<l.size();i++)
                {
                    str.append(l.get(i)).append("\n");
                }
                
                gui.getEditorPane().setText(str.toString());
                HighlightedDocument hDoc = (HighlightedDocument)gui.getEditorPane().getDocument();
                hDoc.colorAll();
                
            } 
            catch (Exception ex)
            {
                Logger.getLogger(OpenActionListener.class.getName()).log(Level.SEVERE,
                        null, ex);
            }
        }
    }
    
}
